package org.example.finalsecurities.service;

import lombok.extern.slf4j.Slf4j;
import org.example.finalsecurities.entity.CrawlerLog;
import org.example.finalsecurities.entity.NewStockCalendarInfo;
import org.example.finalsecurities.mapper.CalendarMapper;
import org.example.finalsecurities.utils.CrawlerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class CalendarService {
    @Autowired
     private CalendarMapper calendarMapper;
    @Autowired
     private CrawlerLogService crawlerLogService;



    public List<NewStockCalendarInfo> selectAll(){
        return calendarMapper.selectAll();
    }
    public void insertOrUpdate(NewStockCalendarInfo newStockCalendarInfo) {
                 NewStockCalendarInfo newStockCalendarInfo1 = calendarMapper.selectById(newStockCalendarInfo.getId());
            if(newStockCalendarInfo1 != null){
                calendarMapper.updateById(newStockCalendarInfo);
            }else{
                log.info("插入前");
                calendarMapper.insert(newStockCalendarInfo);
                log.info("插入后");
            }

    }

    public void fetchAndUpdateCalendar(){
        Date startTime = new Date();
        log.info("开始爬取上市日历数据: {}", startTime);
        //构建请求参数
        CrawlerLog crawlerLog = new CrawlerLog();
        crawlerLog.setActionDesc("爬取新股上市日历");
        crawlerLog.setUrl("https://vip.stock.finance.sina.com.cn/corp/go.php/vRPD_NewStockIssue/page/1.phtml");
        crawlerLog.setStartTime(startTime);
        //爬取数据
        List<NewStockCalendarInfo> newStockCalendarInfos = CrawlerUtil.crawlNewStockCalendar();
        for (NewStockCalendarInfo newStockCalendarInfo : newStockCalendarInfos){
            insertOrUpdate(newStockCalendarInfo);
        }
        //保存爬取日志
        Date endTime = new Date();

        crawlerLog.setEndTime(endTime);
        crawlerLog.setCreateTime(endTime);
        crawlerLog.setUpdateTime(endTime);

         crawlerLogService.saveLog(crawlerLog);
         log.info("爬取新股上市日历数据完成，本次爬虫日志: {}",crawlerLog);
    }
    public void delete(){
        calendarMapper.delete();
    }





}
